<?php
declare (strict_types=1);

namespace app\sysuser\controller;

use app\common\controller\SysBackend;
use app\common\facade\Token;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;
use Throwable;

class Login extends SysBackend
{
    protected array $noNeedLogin = ['logout', 'login'];
    protected array $noNeedPermission = [];

    /**
     * 管理员登录
     * @return void
     * @throws Throwable
     */
    public function login(): void
    {
        $param = $this->request->param(['username' => '', 'password' => '']);
        try {
            $validate = Validate::rule([
                'username' => ValidateRule::isRequire(null, '请输入用户名'),
                'password' => ValidateRule::isRequire(null, '请输入密码')
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $res = $this->auth->login($param['username'], $param['password']);
            if (!$res) {
                throw new ValidateException($this->auth->getError());
            }
        } catch (ValidateException|PDOException|Exception $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', $res);

    }

    /**
     * 管理员注销
     * @return void
     */
    public function logout(): void
    {
        if ($this->request->isPost()) {
            $refreshToken = $this->request->post('refreshToken', '');
            if ($refreshToken) Token::delete((string)$refreshToken);
            $this->auth->logout();
            $this->success();
        }
    }
}
